import os
import json
import requests
from function.dbutil import mysql


class MysqlPoolHandler(object):
    def __init__(self):
        self.pools = {}
        self.connect_ins = {}

    def create_pool(self, ds_id, host, port, user, passwd, db):
        if ds_id in self.pools.keys():
            return self.pools[ds_id]
        try:
            pool = mysql.PymysqlPool(host, port, user, passwd, db)
            self.pools[ds_id] = pool
            return pool
        except Exception as err:
            raise err

    def load_connetc(self, ds_id):
        ds_server_url = os.getenv("dsServerUrl")
        if ds_server_url == "" or ds_server_url is None:
            raise Exception("please set env param [dsServerUrl]")
        r = requests.get("%s/api/t_ds_datasource/findOne?_where=(id,eq,%d)" % (ds_server_url, ds_id))
        if r.status_code != 200:
            raise Exception("find error when request t_ds_datasource")
        result = r.json()
        if len(result) != 1:
            raise Exception("t_ds_datasource not found")
        connection_params = result[0]['connection_params']
        connection = json.loads(connection_params)
        host = connection['host']
        port = connection['port']
        user = connection['user']
        password = connection['password']
        database = connection['database']
        return self.create_pool(ds_id, host, port, user, password, database)
